package org.wzl.personalwebsite.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.wzl.personalwebsite.enumerate.RespCode;
import org.wzl.personalwebsite.utils.JsonWrapperUtil;
import org.wzl.personalwebsite.utils.Resp;

/**
 * @author 卫志龙
 * @version 1.0
 * @date 2024/9/22 9:56
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头获取token
        String token = request.getHeader("token");

        // 判断token是否为空或无效
        if (token == null || token.isEmpty()) {
            // 设置自定义返回内容
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpServletResponse.SC_OK);  // 设置HTTP状态码为401
            response.getWriter().write(JsonWrapperUtil.toJson(Resp.fail(RespCode.NO_TOKEN)));
            return false;  // 拦截请求
        }

        // 如果token存在且有效，放行请求
        return true;
    }

}
